package cn.cm.controller;

import cn.cm.config.OutData;
import cn.cm.dao.SysUserDao;
import cn.cm.entity.SysUser;
import cn.cm.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author shikundai
 * @date 2021/6/22
 * @time 20:39
 * @description: 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private UserService userService;
    /**
     * 描述：添加用户信息
     * @author shikundai
     * @date 2021/6/22
     * @time 20:50
     */
    @PostMapping("/add")
    public OutData addUser(@RequestBody SysUser sysUser){


        System.out.println(sysUser.getName()+"  "+sysUser.getPassword());

       /*
       * 调用持久化层把数据插入到数据库
       * 注意：正常情况下应该是在控制器层中调用业务逻辑层，
       * 此处是为了你们更快的看到效果，
       * 所以省去了业务逻辑层
       * */
//        sysUserDao.insert(sysUser);

        return userService.addUser(sysUser);
    }

    /**
     * 描述：获取所有用户信息
     * @author shikundai
     * @date 2021/6/23
     * @time 20:53
     */
    @GetMapping("/userList")
    public OutData getAllUsers(){
        return userService.getAllUsers();
    }
    /**
     * 描述：用户登录操作
     * @author shikundai
     * @date 2021/6/29
     * @time 10:47
     */
    @PostMapping("/login")
    public OutData login(@RequestBody SysUser sysUser){
        UsernamePasswordToken token=new UsernamePasswordToken(sysUser.getName(),sysUser.getPassword());
        //调用Shiro登录
        SecurityUtils.getSubject().login(token);
        //返回信息
        OutData outData=new OutData();
        outData.setMsg("用户登录成功！");
        return outData;
    }
    /**
     * 描述：用户登出
     * @author shikundai
     * @date 2021/6/29
     * @time 10:50
     */
    @GetMapping("/logOut")
    public OutData logOut(){
        //调用Shiro登出
        SecurityUtils.getSubject().logout();
        OutData outData=new OutData();
        outData.setMsg("用户登出成功！");
        return outData;
    }
    /**
     * 描述：获取登录的用户信息
     * @author shikundai
     * @date 2021/6/29
     * @time 11:12
     */
    @GetMapping("/getLoginUser")
    public OutData getLoginUser(){
        //从认证的Shiro里面获取认证的用户信息
        SysUser sysUser= (SysUser) SecurityUtils.getSubject().getPrincipal();
        //把用户数据放到封装的字段里并返回
        OutData outData=new OutData();
        outData.setData(sysUser);
        return outData;
    }
}
